package 删除链表的倒数第N个结点;

import java.util.Arrays;
import java.util.List;

public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();

        int[] list = new int[]{1};
        ListNode listNode = new ListNode(list[list.length -1]);
        for (int i = list.length - 2; i >= 0; i--) {
            int data = list[i];
            listNode = new ListNode(data, listNode);
        }

        solution.removeNthFromEnd(listNode,1);


    }

    public ListNode removeNthFromEnd(ListNode head, int n)  {
        int index1 = 0;
        int index2 = 0;
        ListNode temp = head;


        if(temp.next != null) {

            while (temp.next != null) {
                temp = temp.next;
                index2++;
                if (index2 - index1 == n + 1) {
                    index1++;
                }
            }
            int index = 0;
            temp = head;
            while(index < index1){
                temp = temp.next;
                index++;
            }


            if(index2 - index1 >= n) {
                temp.next = temp.next.next;
            }
            else{
                head = temp.next;
            }
            return head;
        }
        else{
            return null;
        }
    }



    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
